package com.madixin.chat.controller;

import com.madixin.chat.constants.Constants;
import com.madixin.chat.constants.ValidConstants;
import com.madixin.chat.dto.LoginDto;
import com.madixin.chat.dto.ResponseResult;
import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.exception.ErrorCode;
import com.madixin.chat.service.impl.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;

    /**
     * 登录方法
     *
     * @param loginDto 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ResponseResult<String> login(@RequestBody LoginDto loginDto) {
        if (StringUtils.isBlank(loginDto.getPhone()) || loginDto.getPhone().length() > ValidConstants.PHONE_MAX_SIZE) {
            return ResponseResult.fail("Invalid phone", ErrorCode.ILLEGAL_PARAM);
        }
        if (StringUtils.isBlank(loginDto.getPassword()) || loginDto.getPassword().length() > ValidConstants.PASSWORD_MAX_SIZE || loginDto.getPassword().length() < ValidConstants.PASSWORD_MIN_SIZE) {
            return ResponseResult.fail("Invalid password", ErrorCode.ILLEGAL_PARAM);
        }

        try {
            // 返回JWT令牌
            return ResponseResult.success(loginService.login(loginDto.getPhone(), loginDto.getPassword()));
        } catch (ChatBaseException e) {
            LOGGER.error(e.getMessage());
            return ResponseResult.fail(e.getErrorCode());
        }
    }

    /**
     * 用户注销
     *
     * @return 注销结果
     */
    // @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "user token", required = true, paramType = "header", dataTypeClass = String.class),})
    @PostMapping("/logout")
    public ResponseResult<String> logout() {
        try {
            loginService.logout();
            return ResponseResult.success(Constants.SUCCESS);
        } catch (ChatBaseException e) {
            LOGGER.error("fail to logout:", e);
        } catch (Exception e) {
            LOGGER.error("fail to logout:", e);
        }
        return ResponseResult.success(Constants.FAIL);
    }
}
